package com.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import hyl.core.MyFun;

/**
 * Servlet Filter implementation class Anquan <url-pattern>*.jsp</url-pattern>
 * <url-pattern>*.do</url-pattern> <url-pattern>/u/*</url-pattern>
 * <url-pattern>/s/*</url-pattern> <url-pattern>/f/*</url-pattern>
 */
@WebFilter(urlPatterns = { "*.jsp", "*.do", "/u/*", "/s/*", "/f/*" }, filterName = "apiFilter")
public class MyFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public MyFilter() {
		System.out.println("实例化过滤器");
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		// System.out.println("lll的"+((HttpServletRequest) request).getRequestURI());
		((HttpServletRequest) request).getSession(false);
		((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
		((HttpServletResponse) response).setHeader("Access-Control-Allow-Headers",
				"Content-Type,token,Origin, X-Requested-With,Accept"); // 加入支持自定义的header
		((HttpServletResponse) response).setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
		((HttpServletResponse) response).setHeader("Content-Type", "application/json;charset=utf-8");
		MyFun.print("调用过滤器 doFilter\r\n", ((HttpServletRequest) request).getRequestURI());
		chain.doFilter(request, response);

	}

	// ((HttpServletResponse ) response).setHeader("X-Powered-By"," 3.2.1");
	// response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,token");
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("初始化过滤器");
	}

}
